import { Controller } from "egg";
import { IndexCondition } from "../common";

export default class DrugController extends Controller {
  public async index() {
    const { ctx } = this;
    const { pageSize, pageIndex, name } = ctx.query;
    const _listCondition: IndexCondition = {
      select: "id name brand standard price entryPrice factory createdAt",
      find: {
        is_delete: false,
        ...(name && { name: { $regex: name, $options: "i" } }),
      },
      ...(pageIndex && { pageIndex: parseInt(pageIndex) - 1 }),
      ...(pageSize && { pageSize: parseInt(pageSize) }),
    };
    const res = await ctx.service.drug.findList(_listCondition);
    ctx.helper.success({ ctx, res });
  }

  public async create() {
    const { ctx, service } = this;
    const res = await service.drug.add(ctx.request.body);
    ctx.helper.success({ ctx, res });
  }

  public async findByCondition() {
    const { ctx } = this;
    const _res = await ctx.service.drug.findByName(ctx.request.body);
    if (!_res) {
      return ctx.helper.error({ ctx, errorType: "commonOperateFail" });
    }
    ctx.helper.success({ ctx, res: _res });
  }
}
